package com.gopay.bis.citic.ebank.operation;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.bank.CiticConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.citic.ebank.pay.CiticB2cMessage;
import com.gopay.common.domain.bank.citic.ebank.query.res.StreamRes;
import com.gopay.common.domain.bank.citic.ebank.query.res.data.CiticB2cStreamDataRes;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.HttpTransport;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class CiticB2cQuery {
	
	private CiticB2cCertHelper citicB2cCerthelper;
	private HttpTransport httpTransportB2C;

	public CiticB2cStreamDataRes query(CiticB2cMessage message)
			throws GopayException {
		try {
			// 对数据进行签名
			String signMessage = (String) citicB2cCerthelper.sign(message);
			String result = "";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("SIGNREQMSG", signMessage);
			BankLogUtils.printB2CQuerySendLog(message, params);
			result = httpTransportB2C.submit(params);
			// 获取返回结果
			StreamRes stream = new StreamRes();
			CiticB2cStreamDataRes dataRes = new CiticB2cStreamDataRes();
			XStream xs = new XStream(new DomDriver());
			xs.autodetectAnnotations(true);
			xs.toXML(stream);
			stream = (StreamRes) xs.fromXML(result, stream);
			BankLogUtils.printB2CQueryBlackLog(message, stream);
			if (!StringUtils.equals(stream.getStatus(), CiticConstants.SUCCESS)) {
				// 查询订单失败
				if (stream.getStatus() == null || "".equals(stream.getStatus())) {
					dataRes.setStatus("FFFF");
				} else {
					dataRes.setStatus(stream.getStatus());
					dataRes.setStatusText(stream.getStatusText());
				}
				return dataRes;
			}
			// 获取data数据
			String data = stream.getData();
			message.setSignMessage(data);
			// 对data进行验签
			String dataXml = (String) citicB2cCerthelper.verify(message);
			// 将dataXml解析为查询对象
			xs.toXML(dataRes);
			dataRes = (CiticB2cStreamDataRes) xs.fromXML(dataXml, dataRes);
			return dataRes;
		} catch (Exception e) {
			BankLogUtils.printB2BQueryExceptionLog(message, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6036);
		}
	}

	public void setCiticB2cCerthelper(CiticB2cCertHelper citicB2cCerthelper) {
		this.citicB2cCerthelper = citicB2cCerthelper;
	}

	public void setHttpTransportB2C(HttpTransport httpTransportB2C) {
		this.httpTransportB2C = httpTransportB2C;
	}

}
